package com.imay.live.activity.dynamics;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.base.activity.BaseActivity;
import com.imay.base.util.StringUtil;
import com.imay.live.R;
import com.imay.live.adapter.DiscoveryIndicatorAdapter;
import com.imay.live.adapter.SearchHistoryAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.SearchFamilyFragment;
import com.imay.live.fragment.SearchTopicFragment;
import com.imay.live.fragment.SearchUserFragment;
import com.imay.live.fragment.discovery.MyFragmentPagerAdapter;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.model.SearchHistoryModel;
import com.imay.live.model.UserModel;
import com.imay.live.view.SearchTitle;
import com.imay.live.view.indicator.Indicator;
import com.imay.live.view.indicator.ScrollIndicatorView;
import com.imay.live.view.indicator.slidebar.ColorBar;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lzx on 2017/05/02 0002.
 */

public class SearchActivity extends BaseActivity {
    private final static String CURRENT_KEY = "current_key";

    public final static int FAMILY = 2;

    private RecyclerView recyclerView;
    private SearchTitle searchTitle;
    private SearchHistoryAdapter mAdapter;
    private ArrayList<MultiItemEntity> mdatas;
    private ScrollIndicatorView mIndicatorView;
    ViewPager mViewPager;
    SearchUserFragment searchUserFragment;
    SearchTopicFragment searchTopicFragment;
    SearchFamilyFragment searchFamilyFragment;
    boolean ischoose;
    List<SearchHistoryModel> searchhislist = new ArrayList<SearchHistoryModel>();

    public static void startActivity(Activity activity) {
        Intent starter = new Intent(activity, SearchActivity.class);
        activity.startActivity(starter);
        activity.overridePendingTransition(R.anim.push_up_in, 0);
    }

    public static void startActivity(Activity activity, int current) {
        Intent starter = new Intent(activity, SearchActivity.class);
        starter.putExtra(CURRENT_KEY, current);
        activity.startActivity(starter);
        activity.overridePendingTransition(R.anim.push_up_in, 0);
    }

    @Override
    protected View getCustomTitleBar() {
        searchTitle = new SearchTitle(SearchActivity.this);
        return searchTitle;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.search_layout;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        mViewPager = $(R.id.searchviewpager);
        recyclerView = $(R.id.recyclerView);
        mIndicatorView = $(R.id.siv_tab);


        WrapContentLinearLayoutManager wrapContentLinearLayoutManager
                = new WrapContentLinearLayoutManager(this);
        recyclerView.setLayoutManager(wrapContentLinearLayoutManager);
        recyclerView.setHasFixedSize(true);
        mdatas = new ArrayList<MultiItemEntity>();
        mAdapter = new SearchHistoryAdapter(mdatas);
        mAdapter.bindToRecyclerView(recyclerView);
        recyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_h_content) {
                    Object o = adapter.getItem(position);
                    SearchHistoryModel searchHistoryModel;
                    if (o instanceof SearchHistoryModel) {
                        searchHistoryModel = (SearchHistoryModel) o;
                    } else {
                        return;
                    }

                    setDefault();
                    showResultView();

                    ischoose = true;
                    String c;
                    if (searchHistoryModel.getSpanstring() == null) {
                        c = searchHistoryModel.getString();
                    } else {
                        c = searchHistoryModel.getSpanstring().toString();
                    }
                    searchTitle.getEditText().setText(c);
                    searchText(c);
                    ischoose = false;
                }
            }
        });
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .size(0)
                .build());
        String[] tabTitles = new String[]{getString(R.string.search_user), getString(R.string.search_topic), getString(R.string.search_family)};
        ColorBar colorBar = new ColorBar(SearchActivity.this, getResources().getColor(R.color.text_8d), (int) getResources().getDimension(R.dimen.size_3dp));
        colorBar.setWidth((int) getResources().getDimension(R.dimen.tab_ind_w));
        mIndicatorView.setScrollBar(colorBar);
        DiscoveryIndicatorAdapter mIndicatorAdapter = new DiscoveryIndicatorAdapter(SearchActivity.this, getSupportFragmentManager(), tabTitles, R.layout.view_indicator_search);
        mIndicatorView.setAdapter(mIndicatorAdapter.getIndicatorAdapter());
        mIndicatorView.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View selectItemView, int select, int preSelect) {
                if (select == 0) {
                    MobclickAgent.onEvent(SearchActivity.this, "search_click_user");
                    searchTitle.setHint(getString(R.string.search_hint));
                } else if (select == 1) {
                    MobclickAgent.onEvent(SearchActivity.this, "search_click_topic");
                    searchTitle.setHint(getString(R.string.search_hint));
                } else {
                    MobclickAgent.onEvent(SearchActivity.this, "search_click_family");
                    searchTitle.setHint(getString(R.string.search_hint_family));
                }
                mViewPager.setCurrentItem(select);
            }
        });

        final List<Fragment> fragmentList = new ArrayList<Fragment>();
        searchUserFragment = SearchUserFragment.newInstance();
        searchTopicFragment = SearchTopicFragment.newInstance();
        searchFamilyFragment = SearchFamilyFragment.newInstance();
        fragmentList.add(searchUserFragment);
        fragmentList.add(searchTopicFragment);
        fragmentList.add(searchFamilyFragment);
        mViewPager.setOffscreenPageLimit(2);

        mViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList, tabTitles));

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {
                /** 标注当前页面 **/
                mIndicatorView.setCurrentItem(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        mViewPager.setCurrentItem(getIntent().getIntExtra(CURRENT_KEY, 0));
        searchTitle.setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mViewPager.getCurrentItem() < 2) {
                    if (ischoose) {
                        return;
                    }
                    if (s.length() > 0) {
                        mdatas.clear();
                        loadTextChanged(s.toString());
                        showHisView();
                    } else {
                        showResultView();
                    }
                } else {
                    loadTextChanged(s.toString());
                }
            }
        });
        searchTitle.setCancleOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (TextUtils.isEmpty(searchTitle.getEditText().getText().toString())) {
//                    if (recyclerView.getVisibility() == View.VISIBLE) {
//                        showResultView();
//                    } else {
                finish();
//                    }
//                } else {
//                    searchText();
//                }
            }
        });
        String text = PreferenceHelper.getInstance().getString(PreferenceHelper.SEARCHHIST);
        if (!TextUtils.isEmpty(text)) {
            try {
                ArrayList<SearchHistoryModel> list = JSON.parseObject(text, new TypeReference<ArrayList<SearchHistoryModel>>() {
                }.getType());
                searchhislist.addAll(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void searchText(String str) {
        setDefault();
        showResultView();
        searchUserFragment.searchUser(str, true);
        searchTopicFragment.searchTopic(str);
        for (SearchHistoryModel historyModel : searchhislist) {
            if (historyModel.getString().equals(str)) {
                return;
            }
        }
        SearchHistoryModel historyModel = new SearchHistoryModel();
        historyModel.setString(str);
        if (searchhislist.size() >= 5) {
            searchhislist.remove(searchhislist.size() - 1);
        }
        searchhislist.add(0, historyModel);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ThreadManager.execute(new SaveHistoryThread());
    }

    private class SaveHistoryThread implements Runnable {
        @Override
        public void run() {
            String text = JSON.toJSONString(searchhislist);
            PreferenceHelper.getInstance().putString(PreferenceHelper.SEARCHHIST, text);
        }
    }

    private void showResultView() {
        recyclerView.setVisibility(View.GONE);
        mViewPager.setVisibility(View.VISIBLE);
        mIndicatorView.setVisibility(View.VISIBLE);
    }

    private void hideSoftInputFromWindow() {
        InputMethodManager inputManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        IBinder binder = searchTitle.getEditText().getWindowToken();
        if (binder != null) {
            inputManager.hideSoftInputFromWindow(binder, 0);
        }
    }

    public void setDefault() {
        hideSoftInputFromWindow();
        if (searchTitle != null)
            searchTitle.setmindle();
    }

    private void showHisView() {
        recyclerView.setVisibility(View.VISIBLE);
        mViewPager.setVisibility(View.GONE);
        mIndicatorView.setVisibility(View.GONE);

    }

    private void loadTextChanged(String name) {
        searchUserFragment.searchUser(name, false);
        searchTopicFragment.searchTopic(name);
        searchFamilyFragment.searchFamily(name);
    }

    public void searchResult(ArrayList<UserModel> list, String name) {
        if (recyclerView.getVisibility() == View.GONE) {
            return;
        }
        if (!name.equals(searchTitle.getEditText().getText().toString())) {
            return;
        }
        for (UserModel user : list) {
            if (StringUtil.isEmpty(user.getNick())) {
                continue;
            }
            SearchHistoryModel historyModel = new SearchHistoryModel();
            SpannableString spanstring = new SpannableString(user.getNick());
            for (int i = 0; i < name.length(); i++) {
                int index = user.getNick().indexOf(name.charAt(i));
                if (index > -1) {
                    spanstring.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_50)), index, index + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                }
            }
            historyModel.setSpanstring(spanstring);
            historyModel.setUid(user.getUid());
            mdatas.add(historyModel);
            if (mdatas.size() > 4) {
                break;
            }
        }
        if (!searchhislist.isEmpty()) {
            SearchTitleView searchTitleView = new SearchTitleView("搜索记录");
            mdatas.add(searchTitleView);
            mdatas.addAll(searchhislist);
        }
        mAdapter.notifyDataSetChanged();
    }

    public class SearchTitleView implements MultiItemEntity {
        String title;

        private SearchTitleView(String title) {
            this.title = title;
        }

        public String getTitle() {
            return title;
        }

        @Override
        public int getItemType() {
            return SearchHistoryAdapter.VIEWTYPE_LINEAR_TITLE;
        }
    }
}
